<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader :list="list" @add="addFn"></TodoHeader>
    <TodoMain :list="showList" @del="delFn" @change="changeFn"></TodoMain>
    <TodoFooter
      :list="list"
      :type="type"
      @allDel="allDelFn"
      @changeType="changeType"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // 从本地取出来保存的数据
      list: JSON.parse(localStorage.getItem('todoList')) || [],
      type: 'all',
      // 首先定义type:'all'
    }
  },
  methods: {
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    changeFn(id) {
      const res = this.list.find((item) => item.id === id)
      res.isDone = !res.isDone
    },
    addFn(task) {
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: task,
        isDone: false,
      })
    },
    allDelFn() {
      this.list = this.list.filter((item) => !item.isDone)
    },

    // 通过子组件传入的type来切换要显示的内容
    changeType(type) {
      this.type = type
    },
  },
  computed: {
    // 使用computed,生成新的showList,如果type为yea,那么就从list中将所有已完成的任务放入新数组中
    // type为no就代表将所有未完成的任务放入新的数组中
    showList() {
      if (this.type === 'yes') {
        return this.list.filter((item) => item.isDone)
      } else if (this.type === 'no') {
        return this.list.filter((item) => !item.isDone)
      } else {
        return this.list
      }
    },
  },
  // 监听list的变化,并将变化后的list保存到本地
  watch: {
    list: {
      deep: true,
      handler(newVal) {
        localStorage.setItem('todoList', JSON.stringify(newVal))
      },
    },
  },
}
</script>
